import { Ref, inject } from 'vue'
import { Viewer } from '@/types'
import { Widget } from '@/models'
import { Offset, updateOptions } from '../../widgets/checkbox-group/useBaseDrag'
import { adjustLocation } from '@/models/widget/location'

/** 多选批量拖拽移动 */
export default function useSelectionDrag(data: Ref<Widget>) {
  /** 合同控件 */
  const viewer = inject('Viewer') as Viewer

  /** 初始坐标 */
  let positions: { x: number; y: number; offsets: Offset[] }[] = []

  /** 多选控件列表 */
  let selection: Widget[] | null = null

  /** 清理数据 */
  function clear() {
    selection = null

    positions = []
  }

  return {
    /** 获取初始定位 */
    start(list: Widget[]) {
      if (!list.length) return clear()

      selection = list

      positions = list.map(({ x, y, checkOptions }) => ({
        x,
        y,

        // 单复选框选项位置
        offsets: checkOptions.map(({ x: _x, y: _y }) => ({ x: _x - x, y: _y - y }))
      }))
    },

    /** 移动时同步更新多选控件坐标 */
    move(moveX: number, moveY: number) {
      selection?.forEach((widget, index) => {
        const { x, y, offsets: options } = positions[index]

        Object.assign(widget, { x: x + moveX, y: y + moveY })

        updateOptions(widget, options)

        // 批量控件限制范围
        if (widget.isBatch) adjustLocation(widget)
      })
    },

    /** 拖拽结束修复定位 */
    async stop() {
      if (!selection) return clear()

      const acrossPages = viewer.widgetMovingAcrossPages

      selection.forEach((widget, index) => {
        acrossPages && widget.fixDropLocation()

        widget.adjust()

        const { offsets: options } = positions[index]

        updateOptions(widget, options)

        widget.updateOrigin()
      })

      // 还原多选选中
      viewer.selection.list = [...selection, data.value]

      viewer.selection.lock()

      clear()
    },

    /** 清理数据 */
    clear
  }
}
